<template>
	<div>
		<div>
			<van-nav-bar title="维保预约" left-text="返回" @click-left="back()" left-arrow right-text="维保历史"
				@click-right="goRecord" />
		</div>
		<div>
			<van-form>
				<!-- 维保类型 -->
				<van-field name="radio" label="维保类型" required input-align="right">
					<template #input>
						<van-radio-group v-model="mtType" direction="horizontal" @change="">
							<van-radio name="0">常规保养</van-radio>
							<van-radio name="1">车辆维修</van-radio>
						</van-radio-group>
					</template>
				</van-field>
				<!-- 选择城市 -->
				<van-field v-model="city" name="area" label="城市" placeholder="点击选择城市"
					:rules="[{ required: true, message: '请选择城市' }]" @click="showCity = true" required clickable
					input-align="right" />
				<!-- 选择维修点 -->
				<van-field v-model="station" name="picker" label="维保服务站（4S 店）" placeholder="点击选择维保服务站"
					@click="chooseStation" :rules="[{ required: true, message: '请选择维保服务站' }]" required clickable
					input-align="right" />
				<!-- 选择日期 -->
				<van-field v-model="appointDate" name="calendar" label="预约日期" placeholder="点击选择日期"
					:rules="[{ required: true, message: '请选择日期' }]" @click="showDate = true" required clickable
					input-align="right" />
				<!-- 选择时间 -->
				<van-field v-model="appointTime" name="time" label="时间选择" placeholder="点击选择时间"
					:rules="[{ required: true, message: '请选择时间' }]" @click="chooseTime" required clickable
					input-align="right" />
				<!-- 选择车辆 -->
				<van-field v-model="car" name="picker" label="维保车辆" placeholder="点击选择车辆" required clickable
					@click="showCarList = true" input-align="right" />
				<!-- 地区pop -->
				<van-popup v-model:show="showCity" position="bottom">
					<van-area title="标题" :area-list="areaList" columns-num="2" @confirm="cityConfirm"
						@cancel="showCity = false" />
				</van-popup>
				<!-- 日期pop -->
				<van-calendar v-model="showDate" :min-date="new Date()" @confirm="dateConfirm" />
				<!-- 时间pop -->
				<van-popup v-model:show="showTime" position="bottom">
					<van-datetime-picker type="time" title="选择时间" :min-hour="minHour" :min-minute="minMin"
						@cancel="showTime = false" @confirm="timeConfirm" />
				</van-popup>
				<!-- 维修站pop -->
				<van-popup v-model="showStation" position="bottom">
					<van-picker show-toolbar :columns="columns" @confirm="stationConfirm"
						@cancel="showStation = false" />
				</van-popup>
				<!-- 车辆pop -->
				<van-popup v-model="showCarList" position="bottom">
					<van-picker show-toolbar :columns="carList" @confirm="chooseCar" @cancel="showCarList = false" />
				</van-popup>
			</van-form>
		</div>
		<!-- 维保类型为车辆维修时 -->
		<div v-if="mtType == 1">
			<p style="font-size: 20px; text-align: left;padding: 0px 13px">维修方案</p>
			<van-form>
				<van-field v-model="categoryObj" name="picker" label="选择器" placeholder="点击选择城市"
					@click="showcategoryList = true" />
			</van-form>
			<van-popup v-model="showcategoryList" position="bottom">
				<van-picker show-toolbar :columns="categoryList" @confirm="chooseCategObj"
					@cancel="showcategoryList = false" />
			</van-popup>
		</div>
		<!-- 提交按钮 -->
		<div style="margin: 16px;">
			<van-button style="background-color: #1989fa;" round block type="primary" native-type="submit"
				@click="btn()">
				预约提交
			</van-button>
		</div>
	</div>
</template>

<script>
	import request from '@/util/request'
	import {
		areaList
	} from '@vant/area-data';
	export default {
		name: 'reservation',
		data() {
			return {
				active: '/reservation',
				mtType: '0',
				city: '',
				showCity: false,
				areaList: areaList,
				cityId: 0,
				city: '',
				appointDate: '',
				showDate: false,
				appointTime: '',
				showTime: false,
				minHour: 0,
				minMin: 0,
				stationData: [],
				showStation: false,
				columns: [],
				station: '',
				service: '',
				stationId: '',
				showCarList: false,
				car: '',
				carList: [],
				carData: [],
				carId: '',
				categoryObj: '',
				categoryData: [],
				showcategoryList: false,
				categoryList: [],
				categoryItemData: [],
				showcategoryItem: false,
				categoryItem: [],
			}
		},
		created() {
			this.getCarlist()
			//this.getProg()
		},
		methods: {
			back() {
				this.$router.back()
			},
			goRecord() {
				this.$router.push({
					path: '/service/record'
				})
			},
			typeChange(e) {
				this.mtType = e;
			},
			cityConfirm(e) {
				this.cityId = e[1].code
				this.city = e[1].name
				this.showCity = false;
				this.getStationList()
			},
			dateConfirm(date) {
				this.appointDate = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
				this.showDate = false
			},
			timeConfirm(time) {
				this.appointTime = time
				this.showTime = false
			},
			chooseTime() {
				// console.log(this.currentDate())
				// console.log(this.appointDate)
				// console.log(new Date().getHours() + ':' + new Date().getMinutes())
				if (this.appointDate == this.currentDate()) {
					this.minHour = new Date().getHours()
					this.minMin = new Date().getMinutes()
				} else {
					this.minHour = 0
					this.minMin = 0
				}
				this.showTime = true
			},
			currentDate() {
				let cdate = new Date();
				let year = cdate.getFullYear()
				let mounth = cdate.getMonth() + 1
				let day = cdate.getDate()
				let current = year + '-' + mounth + '-' + day
				return current
			},
			getStationList() {
				request({
					url: '/dev-api/bs-vehicle-owner/maintenance-service-station/page?cityId=' + this.cityId,
					method: 'get'
				}).then(res => {
					// console.log(res)
					this.stationData = res.rows
					let stations = [];
					res.rows.forEach(item => {
						stations.push(item.serviceStationName)
					})
					this.columns = stations
				})
			},
			stationConfirm(e, index) {
				this.station = e;
				this.stationId = this.stationData[index].id;
				this.showStation = false
			},
			chooseStation() {
				if (this.city.length > 0) {
					if (this.stationData.length == 0) {
						this.$toast.fail('该城市暂无服务站，请更换其他城市')
					} else {
						this.showStation = true
					}
				} else {
					this.$toast.fail('请选择城市')
				}
			},
			getCarlist() {
				request({
					url: '/dev-api/bs-vehicle-owner/userCar/queryByUserId/' + JSON.parse(window.localStorage
						.getItem('userInfo')).userId,
					methods: 'get'
				}).then(res => {
					this.carData = res.data
					let columns = []
					res.data.forEach(item => {
						columns.push(item.car.carName + '' + item.car.carModels)
					})
					this.carList = columns
					// console.log(res)
				})
			},
			chooseCar(e, index) {
				this.car = e
				this.carId = this.carData[index].carId;
				this.showCarList = false
			},
			getProg() {
				request({
					url: '/dev-api/bs-vehicle-owner/maintenance-plan/queryMaintenanceItems?maintenanceType=0',
					method: 'get'
				}).then(res => {
					this.categoryData = res.data
					let uniqueCategories = new Set(this.categoryData.map(item => item.category).filter(category =>
						category != null && category != ''));
					this.categoryList = Array.from(uniqueCategories);
					console.log(this.categoryList);
					//this.getProgItem("油液")
				})
			},
			getProgItem(e) {
				request({
					url: 'http://124.93.196.45:10001/dev-api/bs-vehicle-owner/maintenance-plan/list?category=' + e,
					method: 'get'
				}).then(res => {
					this.categoryItemData = res.data
					console.log(this.categoryItemData)
					let uniqueCategories = new Set(this.categoryItemData.map(item => item.replacementPart).filter(
						replacementPart =>
						replacementPart != null && replacementPart != ''));
					this.categoryItem = Array.from(uniqueCategories);
					console.log(this.categoryItem)
				})
			},
			chooseCategObj(e) {

			},
			btn() {
				// console.log(this.mtType)
				// console.log(this.city)
				// console.log(this.stationId)
				// console.log(this.station)
				// console.log(this.appointDate + ' ' + this.appointTime+':00')
				// console.log(this.appointTime)
				// console.log(this.car)
				// console.log(this.carId)
				// console.log(JSON.parse(window.localStorage.getItem('userInfo')).nickName)
				// console.log(JSON.parse(window.localStorage.getItem('userInfo')).phonenumber)
				if (this.mtType == 0) {
					request({
						url: '/dev-api/bs-vehicle-owner/maintenance-appointment',
						method: 'post',
						data: {
							"type": this.mtType,
							"maintenanceServiceStationId": this.stationId,
							"maintenanceServiceStationName": this.station,
							"maintenanceTime": this.appointDate + ' ' + this.appointTime+':00',
							"deliveryTime": this.appointDate + ' ' + this.appointTime+':00',
							"appointTime": this.appointDate + ' ' + this.appointTime+':00',
							"carId": this.carId,
							"customerName": JSON.parse(window.localStorage.getItem('userInfo')).nickName,
							"customerPhone": JSON.parse(window.localStorage.getItem('userInfo')).phonenumber,
						}
					}).then(res => {
							console.log(res)
							if(res.code == 200){
								window.localStorage.setItem("maintenancePaymentId",res.data.paymentId)
								if(window.localStorage.getItem('maintenancePaymentId') != ''){
									this.$toast.success("提交成功")
									this.$router.push({
										path:'/service/pay'
									})
								}
							}else{
								this.$toast.fail("提交失败："+res.msg)
							}
					})
				} else {
					console.log("该功能还未完善")
				}
			}
		}
	}
</script>

<style>
</style>
